<template>
  <div class="student-manage">
    <el-card>
      <div class="card-header">
        <h2>学生管理</h2>
        <div>
          <el-button type="primary" @click="showAddStudentDialog = true">添加学生</el-button>
          <el-button @click="fetchStudents">刷新</el-button>
        </div>
      </div>

      <el-table :data="students" border v-loading="loading">
        <el-table-column prop="id_" label="ID" width="80"></el-table-column>
        <el-table-column prop="student_id" label="学号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="balance" label="余额">
          <template #default="scope">
            {{ formatCurrency(scope.row.balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="注册时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleRecharge(scope.row)">充值</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加学生对话框 -->
    <el-dialog title="添加学生" v-model="showAddStudentDialog" @close="resetStudentForm">
      <el-form :model="newStudent" :rules="studentRules" ref="studentFormRef" label-width="80px">
        <el-form-item label="学号" prop="student_id">
          <el-input v-model="newStudent.student_id" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newStudent.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddStudentDialog = false">取消</el-button>
        <el-button type="primary" @click="addStudent" :loading="adding">确定</el-button>
      </template>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog title="学生充值" v-model="showRechargeDialog" @close="resetRechargeForm">
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="100px">
        <el-form-item label="学生信息">
          <el-input :value="rechargeStudentInfo" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前余额">
          <el-input :value="formatCurrency(currentBalance)" disabled>
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number 
            v-model="rechargeForm.amount" 
            :min="1" 
            :step="10"
            :precision="2"
            style="width: 100%"
            placeholder="请输入充值金额"
          >
            <template #append>元</template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRechargeDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRecharge" :loading="recharging">确定充值</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getStudents, createStudent, deleteStudent, rechargeStudent, getStudentById } from '../api/students'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const students = ref([])
const loading = ref(false)
const adding = ref(false)
const recharging = ref(false)

const showAddStudentDialog = ref(false)
const showRechargeDialog = ref(false)

const newStudent = ref({
  student_id: '',
  name: ''
})

const rechargeForm = ref({
  student_id: null,
  amount: 10
})

const currentStudent = ref(null)
const currentBalance = ref(0)

// 表单引用
const studentFormRef = ref(null)
const rechargeFormRef = ref(null)

// 计算属性
const rechargeStudentInfo = computed(() => {
  if (!currentStudent.value) return ''
  return `${currentStudent.value.student_id} - ${currentStudent.value.name}`
})

// 验证规则
const studentRules = ref({
  student_id: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 1, max: 20, message: '学号长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度在 1 到 20 个字符', trigger: 'blur' }
  ]
})

const rechargeRules = ref({
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '充值金额必须大于0', trigger: 'blur' }
  ]
})

// 格式化金额
const formatCurrency = (value) => {
  if (value === undefined || value === null) return '¥0.00'
  return '¥' + parseFloat(value).toFixed(2)
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取学生列表
const fetchStudents = async () => {
  loading.value = true
  try {
    const response = await getStudents()
    students.value = response.data
  } catch (error) {
    ElMessage.error('获取学生列表失败: ' + (error.response?.data?.detail || error.message))
    console.error('获取学生列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置学生表单
const resetStudentForm = () => {
  newStudent.value = {
    student_id: '',
    name: ''
  }
  studentFormRef.value?.clearValidate()
}

// 重置充值表单
const resetRechargeForm = () => {
  rechargeForm.value = {
    student_id: null,
    amount: 10
  }
  currentStudent.value = null
  currentBalance.value = 0
  rechargeFormRef.value?.clearValidate()
}

// 添加学生
const addStudent = async () => {
  if (!studentFormRef.value) return
  
  try {
    await studentFormRef.value.validate()
    adding.value = true
    
    await createStudent(newStudent.value)
    ElMessage.success('添加学生成功')
    showAddStudentDialog.value = false
    await fetchStudents()
  } catch (error) {
    if (error.errors) {
      return
    }
    ElMessage.error('添加学生失败: ' + (error.response?.data?.detail || error.message))
    console.error('添加学生失败:', error)
  } finally {
    adding.value = false
  }
}

// 处理充值
const handleRecharge = async (student) => {
  currentStudent.value = student
  currentBalance.value = student.balance
  rechargeForm.value.student_id = student.id_
  showRechargeDialog.value = true
}

// 确认充值
const confirmRecharge = async () => {
  if (!rechargeFormRef.value) return
  
  try {
    await rechargeFormRef.value.validate()
    
    await ElMessageBox.confirm(
      `确定要为学生 ${currentStudent.value.name} 充值 ${formatCurrency(rechargeForm.value.amount)} 吗？`,
      '确认充值',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    recharging.value = true
    
    const rechargeData = {
      student_id: rechargeForm.value.student_id,
      amount: parseFloat(rechargeForm.value.amount)
    }
    
    await rechargeStudent(rechargeData)
    ElMessage.success('充值成功')
    showRechargeDialog.value = false
    await fetchStudents()
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    ElMessage.error('充值失败: ' + (error.response?.data?.detail || error.message))
    console.error('充值失败:', error)
  } finally {
    recharging.value = false
  }
}

// 处理删除
const handleDelete = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 "${student.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteStudent(student.id_)
    ElMessage.success('删除学生成功')
    await fetchStudents()
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    ElMessage.error('删除学生失败: ' + (error.response?.data?.detail || error.message))
    console.error('删除学生失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.student-manage {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>